const point = require("../models/point")

var express = require('express');
var router = express.Router();

const Prism = require('prismjs');


const formidable = require('formidable');

//返回图片
router.post('/', (req, res, next) => {
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
        if (err) {
            res.json({ 'state': false })
        } else {
            let tmp = fields.content.replace(/(\r\n|\n|\r|<\/code><code>)/g, '<br>')
            const re = /<pre[^>]*><code[^>]*>(.+?)<\/code><\/pre>/g
            let i
            let text = tmp
            while(i = re.exec(tmp)){
                if(!(/@#js#/.test(i[1]) || /class="language-javascript"/.test(i[1]))) {
                    text = text.replace(i[1], `<pre class="code-box"><code class="code-box">${i[1].replace(/(<pre[^>]*>|<code[^>]*>|<\/code>|<\/pre>)/g, '')}</code></pre>`)
                    continue;
                }
                let tmp = i[1].replace(/@#js#/g, '').replace(/<br>/g, '\r\n').replace(/<[^<>]+>/g, '');
                tmp = tmp.replace(/&nbsp;/g, " ").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&").replace(/&quot;/g, '"').replace(/&apos;/g, "'");
                const html = Prism.highlight(tmp, Prism.languages.javascript, 'javascript')
                text = text.replace(i[1], `<pre class="language-javascript"><code class="language-javascript">${html}</code></pre>`)
            }
            // return
            point.updateOne({
                menu: fields.menu,
                _id: fields.pointId
            }, {
                    $set: {
                        title: fields.title,
                        content: text,
                        bloom: fields.bloom,
                        practice: fields.practice,
                    }
                }, (error, doc) => {
                    if (error) {
                        res.json({ 'state': false, 'msg': error });
                    } else {
                        res.json({ 'state': true, 'msg': "ok" });
                    }
                })
        }

    });

});

module.exports = router;